from lxml import etree
import re
from os import system


def tips():
    print('---------- Powered By Bugosng!!!! ----------')
    system("pause")


# 采用对位盲匹配，只要为止对上了，就能匹配完，不然就出错！
def file_transform(filepath_):
    """
    将本地文件读取成可以用的样子
    :param filepath_: 本地保存的html文件
    :return: 可以用xpath等解析的文件
    """
    # 读取html文件信息（在真实代码中是爬取的网页信息）
    file = open(filepath_, 'r', encoding='utf-8')
    content = file.read()
    file.close()
    # 解析HTML文档，返回根节点对象
    html_ = etree.HTML(content)
    return html_


def match_all_questions(html_, subject_=1):
    # 简单获取id属性为hid的h3节点中的文本内容
    # print(html.xpath("//script[@id='timuText0']/text()"))

    # 正式获取: 任意位置td下面的div标签下面的script,但是下面有俩script,得去一个
    # 注意 xpath里面的索引从1开始
    if subject_ == 1:
        ret_ensp = html_.xpath("//td/div/script[1]")
        str1_ = ''  # 定义一个空字符串,用来承接匹配后的字符串，方便re二次匹配
        all_in_one_dict = {}  # 创建空字典，键为所有问题，值，选择题为列表[选项，选项，选项，选项，正确答案]，判断题，问答题为空
        for TD in ret_ensp:
            # 通过xapth()二次解析结果
            # print(t.xpath("text()")[0])  # , ':', t.xpath("@id")[0])  # 文本第1个:属性第一个
            # str1 += t.xpath("text()")[0]
            # 给D选项加个换行,方便re解析
            if 'D. ' in TD.xpath("text()")[0]:
                ad_d = TD.xpath('text()')[0] + '<br>'
                str1_ += ad_d + '\n'
                continue
            str1_ += TD.xpath("text()")[0] + '\n'
        # print(str1_)
        str2_ = str1_.split('\n')
        all_in_one_dict_last = {}
        for i in str2_:
            all_in_one_dict_last[i] = ''
        del all_in_one_dict_last['']  # 删除末行空位
        # print(all_in_one_dict_last)
        return all_in_one_dict_last
    if subject_ == 2:
        ret_ensp = html_.xpath("//td/div/script[1]")
        str1_ = ''
        for TD in ret_ensp:
            if 'D. ' in TD.xpath("text()")[0]:
                ad_d = TD.xpath('text()')[0] + '<br>'
                str1_ += ad_d + '\n'
                continue
            str1_ += TD.xpath("text()")[0] + '\n'
        str2_ = str1_.split('\n')
        all_in_one_dict_last = {}
        for i in str2_:
            all_in_one_dict_last[i] = ''
        del all_in_one_dict_last['']
        return all_in_one_dict_last


def math_all_answers(html_, subject_=1):
    """
    解析文档，获得所有的问题答案，包括了选择、判断、问答！
    :param subject_: 学科代码
    :param html_: html文档对象
    :return: 答案信息列表
    """
    if subject_ == 1:
        # 从html里匹配答案，选择题和判断题
        # 需要注意在问题的匹配中，选择与判断是分开来做的，因为选择有4个选项
        result_ensp = html_.xpath("//td/div/div[last()]/span[1]")  # xpath索引从1开始
        answers = []  # 创建用来承接的列表，直接将选项保存了就，省的二次匹配
        a_b_c_d = re.compile(r"(?P<option>[A-D]+)")
        for span_with_answer in result_ensp:
            try:
                # print(span_with_answer.xpath('text()')[0].replace('\n', '').replace('\t', ''))  # 获取到了半酣正确行的列表
                right_line = span_with_answer.xpath('text()')[0].replace('\n', '').replace('\t', '')
                answer_mid = a_b_c_d.finditer(right_line)  # 用来承接迭代器，看看是不是拿到了我们要的A B C D
                for ans in answer_mid:
                    if len(ans.group('option')) != 0:
                        answers.append(ans.group('option'))
            except IndexError:
                break
        # print(answers_without_wenda)  # 成了，这个列表是包含了非问答题答案
        # 开始匹配问答题，并将其加入到列表里面
        result_with_wenda = html_.xpath("//td/div[4]/div/span[last()]")
        for wenda in result_with_wenda:
            # <br>使得text()返回的列表包含多个值，0则取第一行内容
            # 通过split组成一条字符串，添加到答案列表
            # print('{}'.format(wenda.xpath('text()')))
            # print(wenda.xpath('text()')[1].replace('\n', '').replace('\t', ''))
            answers.append(''.join(wenda.xpath('text()')))
        return answers
    if subject_ == 2:
        result_ensp = html_.xpath("//td/div/div[last()]/span[1]")
        answers = []
        a_b_c_d = re.compile(r"(?P<option>[A-N]+)")
        for span_with_answer in result_ensp:
            try:
                right_line = span_with_answer.xpath('text()')[0].replace('\n', '').replace('\t', '')
                answer_mid = a_b_c_d.finditer(right_line)  # 用来承接迭代器，看看是不是拿到了我们要的A B C D
                for ans in answer_mid:
                    if len(ans.group('option')) != 0:
                        answers.append(ans.group('option'))
            except IndexError:
                break
        result_with_wenda = html_.xpath("//tr/td[3]/textarea")
        dati_obj = re.compile(r"答案：\n(?P<dati>.*?)---------------------\n您的作答：", re.S)
        dati = []
        for wenda in result_with_wenda:
            text = wenda.xpath('text()')[0]
            dati.append(text)
        # print(dati)
        for daan in dati:
            ensp_ret = dati_obj.finditer(daan)
            for i in ensp_ret:
                answers.append(''.join(i.group('dati').replace(r'\n', '')))
            # print(wenda.xpath("text()"))
        return answers
    if subject_ == 3:
        return []
    if subject_ == 3:
        return []


if __name__ == '__main__':
    from union import union_qa

    subject = 2  # 意思是路由交换
    filepath_html = 'D:\\send_to_song\\虚拟化002.html'
    html = file_transform(filepath_html)
    # all_questions = match_all_questions(html, subject)
    # print(len(all_questions))
    all_answers = math_all_answers(html, 1)
    print(all_answers)
    print(len(all_answers))
    # union_dict = union_qa(all_questions, all_answers)
